package com.lagou.client;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.lagou.handler.UserClientHandler;
import com.lagou.register.ServiceRegister;
import com.lagou.request.RpcRequest;

/**
 * 消费者
 */
public class RPCConsumer {

    // 1.创建一个线程池对象 -- 它要处理我们自定义事件
    private static ExecutorService executorService =
        Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    // 2.声明一个自定义事件处理器 UserClientHandler
    private static UserClientHandler userClientHandler;

    // private static Bootstrap bootstrap;

    // 3.编写方法,初始化客户端 ( 创建连接池 bootStrap 设置bootstrap 连接服务器)
    // public static void initClient() throws InterruptedException {
    // // 1) 初始化UserClientHandler
    // userClientHandler = new UserClientHandler();
    // // 2)创建连接池对象
    // EventLoopGroup group = new NioEventLoopGroup();
    // // 3)创建客户端的引导对象
    // bootstrap = new Bootstrap();
    // // 4)配置启动引导对象
    // bootstrap.group(group)
    // // 设置通道为NIO
    // .channel(NioSocketChannel.class)
    // // 设置请求协议为TCP
    // .option(ChannelOption.TCP_NODELAY, true)
    // // 监听channel 并初始化
    // .handler(new ChannelInitializer<SocketChannel>() {
    // protected void initChannel(SocketChannel socketChannel) throws Exception {
    // // 获取ChannelPipeline
    // ChannelPipeline pipeline = socketChannel.pipeline();
    // // 设置编码
    // pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
    // pipeline.addLast(new StringDecoder());
    // // 添加自定义事件处理器
    // pipeline.addLast(userClientHandler);
    // }
    // });
    //
    // }

    // 4.编写一个方法,使用JDK的动态代理创建对象
    // serviceClass 接口类型,根据哪个接口生成子类代理对象; providerParam : "UserService#sayHello#"
    public static Object createProxy(Class<?> serviceClass, final String providerParam) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {serviceClass},
            new InvocationHandler() {
                public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                    // 1)初始化客户端cliet
                    // if (userClientHandler == null) {
                    // initClient();
                    // }

                    // 5)连接服务端
                    // ZkClient zkClient = new ZkClient("127.0.0.1:2181");
                    // List<String> zkClientChildren = zkClient.getChildren("/rpc-provider");
                    // Random random = new Random();
                    // int n = random.nextInt(zkClientChildren.size());
                    // String node = zkClientChildren.get(n);
                    // String data = zkClient.readData("/rpc-provider/" + node);
                    // RpcNode rpcNode = JSON.parseObject(data.getBytes(), RpcNode.class);
                    // bootstrap.connect(rpcNode.getIp(), rpcNode.getPort()).sync();

                    // 2)给UserClientHandler 设置param参数
                    RpcRequest rpcRequest = new RpcRequest();
                    rpcRequest.setRequestId("1");
                    rpcRequest.setClassName(serviceClass.getSimpleName());
                    rpcRequest.setMethodName(method.getName());
                    rpcRequest.setParameters(objects);
                    rpcRequest.setParameterTypes(new Class[] {String.class});

                    userClientHandler = ServiceRegister.getUserClientHandler();

                    userClientHandler.setParam(rpcRequest);

                    // 3).使用线程池,开启一个线程处理处理call() 写操作,并返回结果
                    Object result = executorService.submit(userClientHandler).get();

                    // 4)return 结果
                    return result + " port: " + userClientHandler.getRpcNode().getPort();
                }
            });
    }

}
